package operations

import command.DBUtil

class UserOper {

  case class User(id: Int, name: String, birthday: String, age: Int, idcard: String, english: String)

  //增加
  def add(user: User): Boolean = {
    val con = DBUtil.getConnection()
    try {
      val sql = new StringBuilder()
        .append("insert into element(name,birthday,age,idcard,english)")
        .append("values(?,?,?,?,?)")
      val pstm = con.prepareStatement(sql.toString())
      pstm.setObject(1, user.name)
      pstm.setObject(2, user.birthday)
      pstm.setObject(3, user.age)
      pstm.setObject(4, user.idcard)
      pstm.setObject(5, user.english)
      pstm.executeLargeUpdate() > 0
    } finally {
      con.close()
    }
  }

  //查找
  def sel() {
    val con = DBUtil.getConnection()
    try {
      val statement = con.createStatement()
      val resultSet = statement.executeQuery("select * from element")
      while (resultSet.next()) {
        print(resultSet.getString("id"))
        print(resultSet.getString("name"))
        print(resultSet.getString("birthday"))
        print(resultSet.getString("age"))
        print(resultSet.getString("idcard"))
        print(resultSet.getString("english"))
      }
    } catch {
      case e: Exception => e.printStackTrace()
    }
    finally {
      con.close()
    }
  }

  //删除
  def del(id: Int): Boolean = {
    val conn = DBUtil.getConnection()
    try {
      val sql = "delete from element where id = ?"
      val pstm = conn.prepareStatement(sql)
      pstm.setObject(1, id)
      pstm.executeUpdate() > 0
    } finally {
      conn.close()
    }
  }

  //更新
  def update(user: User): Boolean = {
    val conn = DBUtil.getConnection()
    try {
      val sql = "update element set name = ?,birthday=?,age=?,idcard=?,english=? where id = ?"
      val pstm = conn.prepareStatement(sql.toString())
      pstm.setObject(1, user.name)
      pstm.setObject(2, user.birthday)
      pstm.setObject(3, user.age)
      pstm.setObject(4, user.idcard)
      pstm.setObject(5, user.english)
      pstm.setObject(6, user.id)
      pstm.executeUpdate() > 0
    } finally {
      conn.close()
    }
  }
}